<?php
include("in.php");

if($_SESSION['status'] == 'new')
{
	$_SESSION['tags'] = null;
	$_SESSION['items'] = array();
	$_SESSION['status'] = 'processing';
}

if($_SESSION['tags'] == null)
{
	// get user input
	$twitterUserName = $_SESSION['user'];
	
	// get user data from social media
	$twitter = new Twitter($twitterUserName);
	$tweets = $twitter->getUserTimeline($twitterUserName, null, null, 200);
	
	// parse user data and construct tag cloud
	$words = array();
	foreach ($tweets as $tweet)
	{
		$tempWords = str_word_count($tweet["text"], 1);
		foreach ($tempWords as $tempWord)
		{
			$words[] = $tempWord;
		}
	}
	
	
	// eliminate words that only occur once
	$dupes = array_diff_assoc($words, array_unique($words));
	
	
	// filter leftover words
	$filter = new Filter();
	$filteredWords = $filter->applyFilter($dupes,4);
	
	
	// prioritize tag cloud items
	$scores = array();
	foreach ($filteredWords as $word)
	{
		if (isset($scores[$word]))
		{
			$scores[$word] *= 2;
		}
		else
		{
			$scores[$word] = 1;
		}
	}
	$tags = array();
	foreach ($scores as $key=>$val)
	{
		$tags[] = new Tag($key, $val);
	}
	usort($tags, array("Tag", "compare"));
	
	$_SESSION['toptags'] = array_slice($tags, 0, 20);
	$_SESSION['tags'] = $tags;
	
	echo "10";
		
	die;
}
else
{
	$client = new AmazonECS(AWS_API_KEY, AWS_API_SECRET_KEY, 'com', AWS_ASSOCIATE_TAG);
	$client->returnType(AmazonECS::RETURN_TYPE_ARRAY);
	$client->category('Blended');
	$client->responseGroup('Medium');
	
	$start_time = time();
	$completed = 0;
	$total = count($_SESSION['toptags']);
	
	
	for($i=0;$i<$total;$i++)
	{
		// mind the time, no longer than 15 seconds
		if((time() - $start_time) > 15)
		{
			$perc = floor(90/$total*$completed) + 10;
			echo($perc);
			die;
		}
		
		// skip all searched tags
		if($_SESSION['toptags'][$i]->searched != 0)
		{
			$completed++;
			continue;
		}
		
		// indicate searching
		$_SESSION['toptags'][$i]->searched = 1;
		
		$tag = $_SESSION['toptags'][$i];
		
		$response = $client->search($tag->word);
		
		if(!is_array($response["Items"]["Item"]) || count($response["Items"]["Item"]) == 0)
			continue;
		
		foreach($response["Items"]["Item"] as $result)
		{
			$item = new Item();
			$item->ASIN = $result["ASIN"];
			$item->link = $result["DetailPageURL"];
			$item->image = $result["LargeImage"]["URL"];
			$item->title = $result["ItemAttributes"]["Title"];
			$item->description = $result["EditorialReviews"]["EditorialReview"][0]["Content"];
			$item->score($_SESSION['tags']);
			$_SESSION["items"][] = $item;
		}
		
		// indicate done
		$_SESSION['toptags'][$i]->searched = 2;
		$completed++;
	}
	
	// sort by tag score
	usort($_SESSION['items'], array("Item", "compare"));
	$_SESSION['status'] = 'done';
	echo "done";
}
